import React, { useState, useEffect } from 'react';
import { Button, Input, Space, Popconfirm, message, Tag, Select } from 'antd';
import { 
  PlusOutlined, 
  SearchOutlined, 
  DeleteOutlined, 
  EditOutlined,
  FileTextOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { FilterCard, TableCard } from '@/components/common';
import { QuestionListItem, QuestionType, DifficultyLevel } from '@/types/question';
import { questionService } from '@/services/questionService';

const { Option } = Select;

const QuestionList: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [questions, setQuestions] = useState<QuestionListItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<QuestionType | undefined>();
  const [difficultyFilter, setDifficultyFilter] = useState<DifficultyLevel | undefined>();
  const [bankFilter, setBankFilter] = useState<number | undefined>();

  // 加载题目列表
  const fetchQuestions = async (page = 1) => {
    setLoading(true);
    try {
      const response = await questionService.getQuestions({
        page,
        limit: pagination.pageSize,
        keyword: searchKeyword || undefined,
        type: typeFilter,
        difficulty: difficultyFilter,
        bank_id: bankFilter,
      });
      const data = response.data.data;
      setQuestions(data.results);
      setPagination({
        ...pagination,
        current: page,
        total: data.count,
      });
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchQuestions(1);
  }, [typeFilter, difficultyFilter, bankFilter]);

  // 搜索
  const handleSearch = () => {
    fetchQuestions(1);
  };

  // 删除题目
  const handleDelete = async (id: number) => {
    try {
      await questionService.deleteQuestion(id);
      message.success('删除成功');
      fetchQuestions(pagination.current);
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 题型映射
  const questionTypeMap: Record<string, string> = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    composite: '综合题',
  };

  // 难度映射
  const difficultyMap: Record<number, { text: string; color: string }> = {
    1: { text: '非常简单', color: 'green' },
    2: { text: '简单', color: 'blue' },
    3: { text: '中等', color: 'orange' },
    4: { text: '困难', color: 'red' },
    5: { text: '非常困难', color: 'purple' },
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '题目标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
      render: (text: string, record: QuestionListItem) => (
        <a onClick={() => navigate(`/admin/question/edit/${record.id}`)}>
          {text || '(无标题)'}
        </a>
      ),
    },
    {
      title: '题型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color="cyan">{questionTypeMap[type] || type}</Tag>
      ),
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 100,
      render: (difficulty: number) => {
        const config = difficultyMap[difficulty] || { text: '未知', color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '所属题库',
      dataIndex: 'question_bank_name',
      key: 'question_bank_name',
      width: 150,
      render: (name: string) => name || <Tag>未分类</Tag>,
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 200,
      render: (tags: string[]) => (
        <>
          {tags?.map((tag, idx) => (
            <Tag key={idx} style={{ marginBottom: 4 }}>{tag}</Tag>
          ))}
        </>
      ),
    },
    {
      title: '使用',
      dataIndex: 'use_count',
      key: 'use_count',
      width: 80,
    },
    {
      title: '正确率',
      dataIndex: 'correct_rate',
      key: 'correct_rate',
      width: 100,
      render: (rate: number) => `${(rate * 100).toFixed(1)}%`,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_: any, record: QuestionListItem) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => navigate(`/admin/question/view/${record.id}`)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => navigate(`/admin/question/edit/${record.id}`)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此题目吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <FilterCard
        pageTitle={
          <Space>
            {id && (
              <Button 
                icon={<ArrowLeftOutlined />} 
                onClick={() => navigate('/admin/question/banks')}
              >
                返回题库列表
              </Button>
            )}
            <span>{bank ? bank.name : '题目管理'}</span>
          </Space>
        }
        titleIcon={<FileTextOutlined />}
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={() => navigate(`/admin/question/create${id ? `?bank_id=${id}` : ''}`)}
          >
            新建题目
          </Button>
        }
      >
        <Space size="middle" wrap>
          <Input
            placeholder="搜索题目标题或内容"
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onPressEnter={handleSearch}
            prefix={<SearchOutlined />}
            style={{ width: 250 }}
          />

          <Select
            placeholder="题型筛选"
            style={{ width: 150 }}
            allowClear
            value={typeFilter}
            onChange={setTypeFilter}
          >
            <Option value="single_choice">单选题</Option>
            <Option value="multiple_choice">多选题</Option>
            <Option value="true_false">判断题</Option>
            <Option value="fill_blank">填空题</Option>
            <Option value="composite">综合题</Option>
          </Select>

          <Select
            placeholder="难度筛选"
            style={{ width: 150 }}
            allowClear
            value={difficultyFilter}
            onChange={setDifficultyFilter}
          >
            <Option value={1}>非常简单</Option>
            <Option value={2}>简单</Option>
            <Option value={3}>中等</Option>
            <Option value={4}>困难</Option>
            <Option value={5}>非常困难</Option>
          </Select>

          <Button type="primary" onClick={handleSearch}>
            搜索
          </Button>
        </Space>
      </FilterCard>

      <TableCard
        tableProps={{
          columns,
          dataSource: questions,
          rowKey: 'id',
          loading,
          pagination: {
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: (page) => {
              setPagination({ ...pagination, current: page });
              fetchQuestions(page);
            },
          },
        }}
      />
    </div>
  );
};

export default QuestionList;

